/**
 * date: 2010-08-30
 */
package com.epro.dx.activity;

import java.io.File;
import java.lang.Thread.UncaughtExceptionHandler;
import java.util.Calendar;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;
import java.util.Map.Entry;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnDismissListener;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.graphics.Color;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.text.TextUtils;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import cn.jpush.android.api.JPushInterface;
import cn.jpush.android.api.TagAliasCallback;

import com.epro.dx.R;
import com.epro.dx.task.GetTopCategoryAsyncTask;
import com.epro.dx.util.ActivityUtil;
import com.epro.dx.util.AsyncTaskUtil;
import com.epro.dx.util.GlobalConfig;
import com.epro.dx.util.OnekeyFilterLocalUtil;
import com.epro.dx.widget.WaitingDialog;
import com.google.android.gms.analytics.HitBuilders;
import com.google.android.gms.analytics.HitBuilders.EventBuilder;
import com.google.android.gms.analytics.HitBuilders.ScreenViewBuilder;
import com.google.android.gms.analytics.Tracker;
import com.umeng.analytics.MobclickAgent;
import com.weipu.common.DXApplication;
import com.weipu.common.DXApplication.TrackerName;
import com.weipu.common.constants.Constant;
import com.weipu.common.constants.ServerConstant;
import com.weipu.common.facade.model.task.TaskType;
import com.weipu.common.facade.support.service.TaskExecutor;
import com.weipu.common.facade.support.service.task.ClearDataTask;
import com.weipu.common.util.Logger;
import com.weipu.common.util.StringUtil;

/**
 * 所有页面基类
 *
 * @author hjd008
 * @version [版本号, 2015-1-6]
 * @see [相关类/方法]
 * @since [产品/模块版本]
 */
@SuppressLint("NewApi")
public class BaseFragmentActivity extends FragmentActivity {

    private static final String TAG = BaseFragmentActivity.class
            .getSimpleName();

    /**
     * topbar 左侧内容
     */
    public TextView topbarLeftTv;

    /**
     * topbar title
     */
    public TextView topbarTitleTv;

    /**
     * topbar 右侧内容
     */
    public TextView topbarrightTv;

    public RelativeLayout titleLayout;

    /**
     * 加载动画对话框
     */
    private WaitingDialog mWaitingDialog;

    /**
     * 是否初始化浏览目录
     */
    protected static boolean ifborwseinit = Boolean.TRUE;

    //数据为空页面
    protected LinearLayout emptyLayout;
    //请求加载页面
    private LinearLayout loadingLayout;
    //数据为空页面描述
    private TextView emptyContent;
    //错误类型标题
    private TextView errorTitle;
    //错误描述
    private TextView errorContent;
    //重试按钮
    protected Button retryBtn;

    private ImageView errorIcon;

    private Toast mToast = null;

    /**
     * 用于保存和清空国家列表
     */
    public static SharedPreferences countryPreferences;

    protected Tracker theTracker;

    protected ScreenViewBuilder screenViewBuilder;

    //极光推送设置别名的次数
    private int setAliasAndTagsTimes = 0;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // setException();
        DXApplication.getContext().addActivityToLists(this);
        theTracker = DXApplication.getContext().getTracker(TrackerName.APP_TRACKER);
        screenViewBuilder = new HitBuilders.ScreenViewBuilder();
        eventBuilder = new HitBuilders.EventBuilder();
        setStateColor();
    }

    protected void setStateColor() {
        //判断安卓版本5.0以上设置沉浸式状态栏
        ActivityUtil.setStatusColor(this, ServerConstant.STATUSCOLOR, null);
    }

    /**
     * 发送屏幕浏览
     *
     * @see [类、类#方法、类#成员]
     */
    protected void sendScreen() {
        theTracker.setScreenName(this.getClass().getSimpleName());
        // Send a screen view.
        theTracker.send(screenViewBuilder.build());
    }

    /**
     * @param action
     * @param category
     * @创建：Tony 2016-5-10上午10:31:01
     * @描述：发送跟踪事件
     */
    protected void sendGAEvent(String action) {
        eventBuilder.setAction(action);
        eventBuilder.setCategory(this.getClass().getSimpleName());
        theTracker.send(eventBuilder.build());
    }

    /**
     * 吐司提示 避免连续弹出长时间不消失
     *
     * @param message
     */
    protected void showToast(String message) {
        if (mToast == null) {
            mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        } else {
            mToast.cancel();
            mToast = Toast.makeText(this, message, Toast.LENGTH_SHORT);
        }
        mToast.show();
    }

    // 设置全局异常，避免FC问题
    public void setException() {
        Thread.setDefaultUncaughtExceptionHandler(new UncaughtExceptionHandler() {
            @Override
            public void uncaughtException(Thread thread, Throwable ex) {
//				Log.e("Error", "uncat Exception, thread: " + thread.getId()
//						+ "," + thread.getName(), ex);
                MobclickAgent.reportError(getApplicationContext(), ex);
                MobclickAgent.onKillProcess(getApplicationContext());
                System.exit(1);
            }
        });
    }

    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        titleLayout = (RelativeLayout) findViewById(R.id.title_layout);
        topbarLeftTv = (TextView) findViewById(R.id.topbar_left_tv);
        topbarTitleTv = (TextView) findViewById(R.id.topbar_title_tv);
        topbarrightTv = (TextView) findViewById(R.id.topbar_right_tv);
        if (null != topbarTitleTv) {
            topbarTitleTv.setFocusable(true);
            topbarTitleTv.requestFocus();
        }
        emptyLayout = (LinearLayout) findViewById(R.id.layout_empty);
        if (null != emptyLayout) {
            errorTitle = (TextView) findViewById(R.id.error_type);
            errorIcon = (ImageView) findViewById(R.id.pic_empty);
            errorContent = (TextView) findViewById(R.id.tv_empty);
            retryBtn = (Button) findViewById(R.id.try_again);
        }
        loadingLayout = (LinearLayout) findViewById(R.id.loading_layout);
        setViewState();
    }

    protected void setViewState() {
    }

    /**
     * 设置标题栏样式
     *
     * @param bgColorId    标题栏背景色
     * @param backBgId     标题栏返回按钮颜色
     * @param titleColorId 标题栏字体颜色
     */
    protected void setTitleStyle(int bgColorId, int backBgId, int titleColorId) {
        titleLayout.setBackgroundColor(backBgId);
        topbarLeftTv.setTextColor(backBgId);
        topbarTitleTv.setTextColor(titleColorId);
    }

    /**
     * 展示加载页面
     *
     * @param view
     */
    protected void showLoadingLayout(View view) {
        if (null != view) {
            view.setVisibility(View.GONE);
        }
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.GONE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.VISIBLE);
        }
    }

    /**
     * 展示错误页面(错误界面更空界面共用同一界面)
     *
     * @param view
     */
    protected void showErrorLayout(View view, int titleId, int contentId, int resId) {
        if (null != view) {
            view.setVisibility(View.GONE);
        }
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.VISIBLE);
            if (titleId != 0) {
                errorTitle.setVisibility(View.VISIBLE);
                errorTitle.setText(titleId);
            } else {
                errorTitle.setVisibility(View.INVISIBLE);
            }
            if (contentId != 0) {
                errorContent.setVisibility(View.VISIBLE);
                errorContent.setText(contentId);
            } else {
                errorContent.setVisibility(View.INVISIBLE);
            }
            errorIcon.setImageResource(resId);
            retryBtn.setVisibility(View.VISIBLE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    /**
     * @param result
     * @param v
     * @创建：Tony 2016-4-14下午2:04:39
     * @描述：根据返回码显示错误页面
     */
    protected void showErrorLayout(String result, View v) {
        if (ServerConstant.ReturnCode.CLIENT_NET_UN_AVAILABLE.equals(result)) {
            showErrorLayout(v, R.string.internet_error, R.string.internet_suggest, R.drawable.no_internet);

        } else {
            showErrorLayout(v, R.string.server_busy, R.string.server_suggest, R.drawable.no_internet);

        }
    }

    /**
     * 展示空数据页面(错误界面更空界面共用同一界面)
     *
     * @param view
     * @param contentId
     * @param resId
     */
    protected void showEmptyLayout(View view, int contentId, int resId) {
        if (null != view) {
            view.setVisibility(View.GONE);
        }
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.VISIBLE);
            errorContent.setText(contentId);
            errorIcon.setImageResource(resId);
            retryBtn.setVisibility(View.GONE);
            errorTitle.setVisibility(View.INVISIBLE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏所有辅助界面
     *
     * @param view
     */
    protected void hideAllLayout() {
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.GONE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 隐藏所有辅助界面 显示数据界面
     *
     * @param view
     */
    protected void hideAllLayout(View view) {
        if (null != view) {
            view.setVisibility(View.VISIBLE);
        }
        if (null != emptyLayout) {
            emptyLayout.setVisibility(View.GONE);
        }
        if (null != loadingLayout) {
            loadingLayout.setVisibility(View.GONE);
        }
    }

    /**
     * 设置topbar 左侧内容
     *
     * @param isBackIcon 是否需要显示返回图标
     * @param resId      string.xml中的资源来设置按钮的内容 -1即不显示文字
     * @return
     * @see [类、类#方法、类#成员]
     */
    protected View setLeftBtnContent(Boolean isBackIcon, int resId) {
        if (!isBackIcon && -1 != resId) {
            return null;
        } else {
            topbarLeftTv.setVisibility(View.VISIBLE);
            topbarLeftTv.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    finish();
                }
            });
            if (isBackIcon) {
                topbarLeftTv.setCompoundDrawablesWithIntrinsicBounds(
                        R.drawable.selector_topbar_back, 0, 0, 0);
            }
            if (-1 != resId) {
                topbarLeftTv.setText(resId);
            }
        }
        return topbarLeftTv;
    }

    /**
     * 设置topbar 左侧内容
     *
     * @param isBackIcon 是否需要显示返回图标
     * @param resId      string.xml中的资源来设置按钮的内容 -1即不显示文字
     * @return
     * @see [类、类#方法、类#成员]
     */
    protected View setLeftBtnToHome(int homeTag) {
        topbarLeftTv.setVisibility(View.VISIBLE);
        topbarLeftTv.setCompoundDrawablesWithIntrinsicBounds(
                R.drawable.selector_topbar_back, 0, 0, 0);
        final Intent intent = new Intent(this, HomeActivity.class);

        intent.putExtra(HomeActivity.CURRENT_TAB_TAG, getString(homeTag));
        topbarLeftTv.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivity(intent);
                finish();
            }
        });

        return topbarLeftTv;
    }

    /**
     * 设置topbar 右侧内容
     *
     * @param resId 通过string.xml中的资源来设置按钮的内容
     * @return
     * @see [类、类#方法、类#成员]
     */
    protected View setRightBtnContent(int resId) {
        topbarrightTv.setVisibility(View.VISIBLE);
        topbarrightTv.setText(resId);
        return topbarrightTv;
    }

    protected View setRightBtnBitmap() {
        // topbarrightTv.setCompoundDrawablesWithIntrinsicBounds(R.drawable.share,
        // 0, 0, 0);
        topbarrightTv.setBackgroundResource(R.drawable.share);
        topbarrightTv.setVisibility(View.VISIBLE);
        // topbarrightTv.setText(resId);
        return topbarrightTv;
    }

    /**
     * 设置topbar title
     *
     * @param resId 通过string.xml资源来设置标题
     * @return
     * @see [类、类#方法、类#成员]
     */
    protected View setTitleContent(int resId) {
        return setTitleContent(getString(resId));
    }

    /**
     * 设置topbar title
     *
     * @param resId 通过string.xml资源来设置标题
     * @return
     * @see [类、类#方法、类#成员]
     */
    protected View setTitleContent(String title) {
        if (!TextUtils.isEmpty(title)) {
            topbarTitleTv.setText(title);
        }
        return topbarTitleTv;
    }

    /**
     * 显示加载对话框
     *
     * @see [类、类#方法、类#成员]
     */
    protected void showWaitingDialog() {
        if (mWaitingDialog == null) {
            mWaitingDialog = new WaitingDialog(this,
                    getString(R.string.loading), true);
            mWaitingDialog.setOnDismissListener(new OnDismissListener() {

                @Override
                public void onDismiss(DialogInterface arg0) {
                    mWaitingDialog = null;
                }
            });
        }
        mWaitingDialog.show();
    }

    /**
     * 隐藏加载对话框
     *
     * @see [类、类#方法、类#成员]
     */
    protected void hideWaitingDialog() {
        if (mWaitingDialog == null || !mWaitingDialog.isShowing()) {
            return;
        }
        mWaitingDialog.dismiss();
    }

    // /**
    // * 添加事件监听
    // * @return void [返回类型说明]
    // * @exception throws [违例类型] [违例说明]
    // * @see [类、类#方法、类#成员]
    // */
    // protected void attachListener()
    // {
    // if (!(this instanceof OnClickListener))
    // {
    // return;
    // }
    //
    // int[] resIds = {R.id.home_button, R.id.brower_button, R.id.mycart_button,
    // R.id.more_button};
    // for (int i = 0; i < resIds.length; i++)
    // {
    // setOnClick(resIds[i]);
    // }
    // }

    // /**
    // * 设置OnClickListener事件监听
    // * @param resId [参数说明]
    // * @return void [返回类型说明]
    // * @exception throws [违例类型] [违例说明]
    // * @see [类、类#方法、类#成员]
    // */
    // protected void setOnClick(int resId)
    // {
    // if (!(this instanceof OnClickListener))
    // {
    // return;
    // }
    // if (null != findViewById(resId))
    // {
    // Bundle data = getIntent().getExtras();
    // String fromActivity = null;
    // if (null != data)
    // {
    // fromActivity =
    // data.getString(ServerConstant.Parameter.PARAMETER_NAME_FROM_ACTIVITY);
    // }
    // findViewById(resId).setOnClickListener((OnClickListener)this);
    // if ((R.id.home_button == resId)
    // && (this.getClass() == HomeActivity.class || this.getClass() ==
    // SearchListActivity.class))
    // {
    // ((Button)findViewById(resId)).setCompoundDrawablesWithIntrinsicBounds(null,
    // getResources().getDrawable(R.drawable.home_dw),
    // null,
    // null);
    // if (this.getClass() == HomeActivity.class && R.id.home_button == resId)
    // {
    // ((Button)findViewById(resId)).setEnabled(false);
    // }
    // }
    // else if (this.getClass() == BrowsListActivity.class && R.id.brower_button
    // == resId
    // || this.getClass() == ProductListActivity.class && R.id.brower_button ==
    // resId)
    // {
    // ((Button)findViewById(resId)).setCompoundDrawablesWithIntrinsicBounds(null,
    // getResources().getDrawable(R.drawable.browse_dw),
    // null,
    // null);
    // if (this.getClass() == BrowsListActivity.class && R.id.brower_button ==
    // resId)
    // {
    // ((Button)findViewById(resId)).setEnabled(false);
    // }
    //
    // }
    // else if (this.getClass() == ShoppingCartActivity.class &&
    // R.id.mycart_button == resId)
    // {
    // ((Button)findViewById(resId)).setCompoundDrawablesWithIntrinsicBounds(null,
    // getResources().getDrawable(R.drawable.cart_dw),
    // null,
    // null);
    // ((Button)findViewById(resId)).setEnabled(false);
    // }
    // else if (this.getClass() == MoreActivity.class && R.id.more_button ==
    // resId
    // || this.getClass() == InfoChildActivity.class && R.id.more_button ==
    // resId)
    // {
    // ((Button)findViewById(resId)).setCompoundDrawablesWithIntrinsicBounds(null,
    // getResources().getDrawable(R.drawable.more_dw),
    // null,
    // null);
    // if (this.getClass() == MoreActivity.class && R.id.more_button == resId)
    // {
    // ((Button)findViewById(resId)).setEnabled(false);
    // }
    // }
    // else if (this.getClass() == DetailActivity.class || this.getClass() ==
    //
    // ProductImageBrowseActivity.class)
    // {
    // if (ServerConstant.ActionConstant.ACTION_NEWMAIN.equals(fromActivity) &&
    // R.id.home_button == resId
    // || ServerConstant.ActionConstant.ACTION_SEARCH_LIST.equals(fromActivity)
    // && R.id.home_button == resId)
    // {
    // ((Button)findViewById(resId)).setCompoundDrawablesWithIntrinsicBounds(null,
    // getResources().getDrawable(R.drawable.home_dw),
    // null,
    // null);
    // }
    // else if
    // (ServerConstant.ActionConstant.ACTION_PRODUCT_LIST.equals(fromActivity)
    // && R.id.brower_button == resId)
    // {
    // ((Button)findViewById(resId)).setCompoundDrawablesWithIntrinsicBounds(null,
    // getResources().getDrawable(R.drawable.browse_dw),
    // null,
    // null);
    // }
    // else if (ServerConstant.ActionConstant.ACTION_MYCART.equals(fromActivity)
    // && R.id.mycart_button == resId)
    // {
    // ((Button)findViewById(resId)).setCompoundDrawablesWithIntrinsicBounds(null,
    // getResources().getDrawable(R.drawable.cart_dw),
    // null,
    // null);
    // }
    // }
    // }
    // }

    /**
     * 返回
     *
     * @param intent [参数说明]
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    protected void back(Intent intent) {
        if (null == intent) {
            Bundle data = getIntent().getExtras();
            intent = new Intent();
            String backAction = null;
            if (null != data) {
                backAction = data
                        .getString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION);
            }

            if (null == backAction) {
                intent.setClass(this, HomeActivity.class);
            } else {
                intent.setAction(backAction);
            }
        }

        startActivity(intent);
        finish();
    }

    // /**
    // * 返回
    // * @param intent [参数说明]
    // * @param back2 上上级返回标识
    // * @return void [返回类型说明]
    // * @exception throws [违例类型] [违例说明]
    // * @see [类、类#方法、类#成员]
    // */
    // private void back(Intent intent, String back2)
    // {
    // if (null == intent)
    // {
    // Bundle data = getIntent().getExtras();
    // intent = new Intent();
    // String backAction = null;
    // String searchKeyWord = null;
    // int productId = -1;
    // String catalogId = null;
    // String catalogName = null;
    // ProductParcelable p =
    // getIntent().getParcelableExtra("product_parcelable");
    // ProductModel product = null;
    // if (null != p)
    // {
    // product = p.getProdcut();
    // }
    // if (null != data)
    // {
    // backAction =
    // data.getString(ServerConstant.Parameter.PARAMETER_NAME_BACK_ACTION);
    // searchKeyWord = data.getString("serchtxt");
    // productId =
    // data.getInt(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID, -1);
    // catalogId = data.getString("catalogId");
    // catalogName = data.getString("catalogname");
    //
    // if (null == backAction)
    // {
    // backAction =
    // data.getString(ServerConstant.Parameter.PARAMETER_NAME_BACK2_ACTION);
    // }
    //
    // }
    // if (null != back2)
    // {
    // Bundle b = new Bundle();
    // b.putString(ServerConstant.Parameter.PARAMETER_NAME_BACK2_ACTION, back2);
    // intent.putExtras(b);
    // }
    // if (null == backAction)
    // {
    // intent.setClass(this, HomeActivity.class);
    // }
    // else
    // {
    // if (null != searchKeyWord)
    // {
    // intent.putExtra("serchtxt", searchKeyWord);
    // }
    // if (-1 != productId)
    // {
    // intent.putExtra(ServerConstant.Parameter.PARAMETER_NAME_PRODUCT_ID,
    // productId);
    // }
    // if (null != catalogId)
    // {
    // intent.putExtra("catalogId", catalogId);
    // }
    // if (null != catalogName)
    // {
    // intent.putExtra("catalogname", catalogName);
    // }
    // if (null != product)
    // {
    // Bundle b = new Bundle();
    // ProductParcelable parcelable = new ProductParcelable(product);
    // // 发送对象
    // b.putParcelable("product_parcelable", parcelable);
    // }
    // intent.setAction(backAction);
    // }
    // }
    // startActivity(intent);
    // finish();
    // }

    /**
     * 将获取的国家码持久化在本地
     *
     * @param country [参数说明]
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    @SuppressWarnings({"rawtypes", "unchecked"})
    public static void persistenceCountry(Map<String, ?> mapCountry) {
        Iterator iterator;
        Editor editor = null;
        iterator = mapCountry.entrySet().iterator();
        editor = countryPreferences.edit();
        while (iterator.hasNext()) {
            Map.Entry<String, String> entry = (Entry<String, String>) iterator
                    .next();
            editor.putString(entry.getKey(), entry.getValue());
        }

        editor.commit();
    }

    /**
     * 注销
     *
     * @return boolean 注销是否成功
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    public void logout() {
        Logger.d(TAG, "logout");
        GlobalConfig.getInstance().setShoppingCartChange(true);
        StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_NAME_IS_LOGIN,
                "false");

        //清除用户的一键过滤设置
        StringUtil.saveConfig(ActivityUtil.getCustomerID() + ServerConstant.OneKeyFilter.ISFILTERKEY_ONLINE, null);
        OnekeyFilterLocalUtil.deleteLocalData(BaseFragmentActivity.this, ActivityUtil.getCustomerID());

        //用户登出清空记住的CID
        StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID, null);
        com.weipu.common.util.GlobalConfig.getInstance().getUserSessionCfg().setCustomerid(null);

        //用户登出清空记住的Token
        StringUtil.saveConfig(ServerConstant.Parameter.PARAMETER_NAME_TOKEN, null);
        com.weipu.common.util.GlobalConfig.getInstance().getUserSessionCfg().setToken(null);

        //极光设置取消别名绑定
        setJPushAlias("", null);

        //更新一级品类信息
        AsyncTaskUtil.executeTask(new GetTopCategoryAsyncTask(BaseFragmentActivity.this, null));

        //更改标记刷新首页推荐数据
        StringUtil.saveConfig("Home_RefreshBFD", "true");
    }

    /**
     * 退出应用程序
     *
     * @return void [返回类型说明]
     * @throws throws [违例类型] [违例说明]
     * @see [类、类#方法、类#成员]
     */
    protected void exit() {
        // 如果已登录则需要注销
//		if (ActivityUtil.isLogin(this)) {
//			logout();
//		}
        Logger.d("NewMainActivity", "exit: ");
        // 退出时删除缓存数据库
//		this.deleteDatabase("webview.db");
//		this.deleteDatabase("webviewCache.db");
        // 退出时删除缓存图片大小为 0的
        long mytime = Calendar.getInstance().getTimeInMillis();
        File file = new File("/data/data/" + this.getPackageName()
                + "/cacheImgFile");
        try {
            File[] files = file.listFiles();
            if (null != files && files.length > 0) {
                for (int i = 0; i < files.length; i++) {
                    File f = files[i];
                    if (f.length() < 2000
                            || mytime - f.lastModified() > Constant.WEEK_MILLIS_TIME) {
                        f.delete();
                    }
                }
            }
        } catch (Exception e) {
            if (Logger.isLog) {
                Logger.d("NewMainActivity", "exit: " + e.getMessage());
            }
        }
        // 用来保存统计数据
        MobclickAgent.onKillProcess(this);
        moveTaskToBack(!isTaskRoot());
        // GlobalConfig.getInstance().setBannerModels(null);
        // 启动后台任务，程序退出清理
        TaskExecutor.doTaskInBackground(new ClearDataTask(
                TaskType.CLEAR_DB_AFTER_EXIT));
        finish();
    }

    public int getDensityDpi() {
        DisplayMetrics metrics = new DisplayMetrics();
        Display display = getWindowManager().getDefaultDisplay();
        display.getMetrics(metrics);
        return metrics.densityDpi;
    }

    @Override
    protected void onStart() {
        super.onStart();
        // TestinAgent.onStart(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onResume(this);
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPause(this);
    }

    @Override
    protected void onStop() {
        super.onStop();
        // TestinAgent.onStop(this);
    }

    @Override
    protected void onDestroy() {
        Logger.d(TAG, "onDestroy.");
        DXApplication.getContext().removeActivityFromLists(this);
        mWaitingDialog = null;
        super.onDestroy();
    }

    public String getCustomerID() {
        // 获取CustomerId
        String customerid = com.weipu.common.util.GlobalConfig.getInstance()
                .getUserSessionCfg().getCustomerid();
        if (null == customerid || "".equals(customerid)) {
            customerid = StringUtil.getConfig(
                    ServerConstant.Parameter.PARAMETER_USER_CUSTOMERID, "0");
        }
        return customerid;
    }

    /**
     * 显示确认放弃付款对话框
     */
    AlertDialog cancelPayDialog = null;

    private EventBuilder eventBuilder;

    protected void showConfirmGiveUpPayDialog() {
        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setMessage(R.string.base_cancel_pay_message);
        builder.setPositiveButton(R.string.btn_yes, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                cancelPayDialog.dismiss();
                finish();
            }
        });
        builder.setNegativeButton(R.string.btn_no, new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface arg0, int arg1) {
                cancelPayDialog.dismiss();
            }
        });

        cancelPayDialog = builder.create();
        cancelPayDialog.show();
    }

    /**
     * 用于登录成功后绑定用户与极光ID
     *
     * @param customerID 用户ID
     * @param category   自定义分组
     */
    protected void setJPushAlias(final String customerID, final Set<String> category) {
        JPushInterface.setAliasAndTags(this, customerID, category, new TagAliasCallback() {

            @Override
            public void gotResult(int responseCode, String alias, Set<String> tags) {
//				Log.d("JPush", "setAliasAndTags_responseCode:  "+responseCode);
                if (6002 == responseCode && setAliasAndTagsTimes < 2) {
                    //第一次设置超时，再试一次
                    ++setAliasAndTagsTimes;
                    setJPushAlias(customerID, category);
                }
            }
        });
    }

    /**
     * @创建：Tony 2016-4-29上午10:48:43
     * @描述：用于消息中心跳转返回
     */
    protected void backToHome() {
        Intent intent = new Intent(this, HomeActivity.class);
        startActivity(intent);
        finish();
    }
}
